const api = require('../../utils/api');

Page({
  data: {
    mealId: '',
    loading: true,
    isLoading: true, // 添加与wxml匹配的属性
    meal: null,
    
    // 餐食信息显示数据
    mealDate: '',
    mealTime: '',
    mealTypeIndex: 0,
    mealTypes: ['早餐', '午餐', '晚餐', '加餐'],
    totalCalories: 0,
    totalCarbs: 0,
    totalProtein: 0,
    totalFat: 0,
    foods: [], // 添加foods数组用于展示
    
    // 编辑模式标记
    isEditing: false,
    
    // 删除确认弹窗
    showDeleteModal: false,
    
    // 可编辑的餐食信息
    editData: {
      date: '',
      time: '',
      mealType: '',
      foods: []
    },
    
    // 餐食类型选项
    mealTypeOptions: ['早餐', '午餐', '晚餐', '加餐'],
    
    // 搜索相关
    showFoodSearch: false,
    searchValue: '',
    searching: false,
    searchResults: [],
    
    // 食物分类
    categories: [],
    currentCategory: '全部',
    
    // 新增刷新标记
    needRefresh: false,
  },
  
  onLoad(options) {
    if (options.id) {
      this.setData({
        mealId: options.id
      });
      
      // 加载餐食详情
      this.loadMealDetail(options.id);
      
      // 加载食物分类
      this.loadFoodCategories();
      
      // 监听来自编辑页面的刷新事件
      const eventChannel = this.getOpenerEventChannel();
      if (eventChannel) {
        eventChannel.on('refreshData', (data) => {
          console.log('收到刷新事件:', data);
          if (data && data.mealId) {
            // 确保使用最新ID
            this.loadMealDetail(data.mealId);
          }
        });
      }
    } else {
      wx.showToast({
        title: '无效的餐食ID',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },
  
  // 页面显示时检查是否需要刷新数据
  onShow() {
    // 如果设置了刷新标记，重新加载数据
    if (this.data.needRefresh && this.data.mealId) {
      console.log('从编辑页面返回，需要刷新数据');
      this.loadMealDetail(this.data.mealId);
      // 重置刷新标记
      this.setData({ needRefresh: false });
    }
  },
  
  // 加载餐食详情
  async loadMealDetail(mealId) {
    this.setData({ loading: true, isLoading: true });
    
    try {
      const result = await api.diet.getMealById(mealId);
      
      if (result && result.success) {
        const meal = result.data;
        
        // 计算餐食类型索引
        const mealTypeIndex = this.data.mealTypes.indexOf(meal.mealType);
        
        // 格式化日期显示
        const dateObj = new Date(meal.date);
        const formattedDate = `${dateObj.getFullYear()}-${String(dateObj.getMonth() + 1).padStart(2, '0')}-${String(dateObj.getDate()).padStart(2, '0')}`;
        
        // 格式化营养素数据，保留一位小数
        const formattedTotalCalories = Math.round(meal.totalCalories || 0);
        const formattedTotalCarbs = Math.round((meal.totalCarbs || 0) * 10) / 10;
        const formattedTotalProtein = Math.round((meal.totalProtein || 0) * 10) / 10;
        const formattedTotalFat = Math.round((meal.totalFat || 0) * 10) / 10;
        
        // 格式化食物数据中的营养素
        const formattedFoods = (meal.foods || []).map(food => {
          return {
            ...food,
            carbs: Math.round(food.carbs * 10) / 10,
            protein: Math.round(food.protein * 10) / 10,
            fat: Math.round(food.fat * 10) / 10
          };
        });
        
        this.setData({
          meal,
          loading: false,
          isLoading: false,
          
          // 设置显示数据
          mealDate: formattedDate,
          mealTime: meal.time,
          mealTypeIndex: mealTypeIndex !== -1 ? mealTypeIndex : 0,
          totalCalories: formattedTotalCalories,
          totalCarbs: formattedTotalCarbs,
          totalProtein: formattedTotalProtein,
          totalFat: formattedTotalFat,
          foods: formattedFoods,
          
          // 初始化编辑数据
          editData: {
            date: formattedDate,
            time: meal.time,
            mealType: meal.mealType,
            foods: formattedFoods.map(food => ({
              ...food,
              quantity: food.quantity || 100,
              unit: food.unit || '克'
            }))
          }
        });
      } else {
        wx.showToast({
          title: '加载失败：无法获取餐食数据',
          icon: 'none'
        });
        this.setData({ loading: false, isLoading: false });
      }
    } catch (error) {
      console.error('加载餐食详情失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      this.setData({ loading: false, isLoading: false });
    }
  },
  
  // 返回上一页
  goBack() {
    wx.navigateBack();
  },
  
  // 加载食物分类
  async loadFoodCategories() {
    try {
      const result = await api.diet.getFoodCategories();
      if (result && result.success) {
        // 添加"全部"分类
        const categories = ['全部', ...result.data];
        
        this.setData({
          categories
        });
      }
    } catch (error) {
      console.error('加载食物分类失败:', error);
    }
  },
  
  // 编辑餐食
  editMeal() {
    // 获取当前餐食ID
    const mealId = this.data.mealId;
    
    // 导航到dietEdit页面并传递参数
    wx.navigateTo({
      url: `/pages/dietEdit/dietEdit?id=${mealId}`,
      events: {
        // 监听编辑页发送回来的数据
        refreshData: (data) => {
          console.log('从编辑页接收到刷新事件:', data);
          if (data && data.mealId) {
            this.loadMealDetail(data.mealId);
          }
        }
      },
      success: (res) => {
        // 编辑页面打开成功
        console.log('编辑页面打开成功');
      }
    });
  },
  
  // 切换到编辑模式
  toggleEditMode() {
    this.setData({
      isEditing: !this.data.isEditing
    });
  },
  
  // 处理日期变更
  onDateChange(e) {
    this.setData({
      'editData.date': e.detail.value
    });
  },
  
  // 处理时间变更
  onTimeChange(e) {
    this.setData({
      'editData.time': e.detail.value
    });
  },
  
  // 处理餐食类型变更
  onMealTypeChange(e) {
    const mealType = this.data.mealTypeOptions[e.detail.value];
    
    this.setData({
      'editData.mealType': mealType
    });
  },
  
  // 显示食物搜索
  showFoodSearch() {
    this.setData({
      showFoodSearch: true,
      searchValue: '',
      searchResults: []
    });
  },
  
  // 隐藏食物搜索
  hideFoodSearch() {
    this.setData({
      showFoodSearch: false
    });
  },
  
  // 显示删除确认对话框
  showDeleteConfirm() {
    this.setData({
      showDeleteModal: true
    });
  },
  
  // 取消删除
  cancelDelete() {
    this.setData({
      showDeleteModal: false
    });
  },
  
  // 确认删除
  confirmDelete() {
    this.deleteMeal();
  },
  
  // 处理搜索输入变化
  onSearchInput(e) {
    this.setData({
      searchValue: e.detail.value
    });
    
    // 如果输入框为空，清空搜索结果
    if (!e.detail.value.trim()) {
      this.setData({
        searchResults: []
      });
    }
  },
  
  // 处理搜索提交
  onSearchSubmit() {
    this.searchFood();
  },
  
  // 搜索食物
  async searchFood() {
    const query = this.data.searchValue.trim();
    if (!query) return;
    
    this.setData({ searching: true });
    
    try {
      const result = await api.diet.searchFoods(
        query,
        this.data.currentCategory !== '全部' ? this.data.currentCategory : null
      );
      
      if (result && result.success) {
        this.setData({
          searchResults: result.data,
          searching: false
        });
      } else {
        this.setData({
          searchResults: [],
          searching: false
        });
        
        wx.showToast({
          title: '未找到匹配的食物',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('搜索食物失败:', error);
      this.setData({ searching: false });
      wx.showToast({
        title: '搜索失败',
        icon: 'none'
      });
    }
  },
  
  // 切换食物分类
  switchCategory(e) {
    const { category } = e.currentTarget.dataset;
    
    this.setData({
      currentCategory: category
    });
  },
  
  // 选择食物
  selectFood(e) {
    const { food } = e.currentTarget.dataset;
    if (!food) return;
    
    // 创建一个新的食物对象，包含数量属性
    const selectedFood = {
      ...food,
      quantity: 100, // 默认数量为100克
      unit: '克',
    };
    
    const foods = [...this.data.editData.foods, selectedFood];
    
    this.setData({
      'editData.foods': foods,
      showFoodSearch: false,
      searchValue: '',
      searchResults: []
    });
  },
  
  // 修改食物数量
  updateFoodQuantity(e) {
    const { index } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    // 检验输入是否为数字
    if (!/^\d*\.?\d*$/.test(value)) return;
    
    const foods = [...this.data.editData.foods];
    
    if (index >= 0 && index < foods.length) {
      foods[index].quantity = value;
      
      this.setData({
        'editData.foods': foods
      });
    }
  },
  
  // 移除食物
  removeFood(e) {
    const { index } = e.currentTarget.dataset;
    const foods = [...this.data.editData.foods];
    
    foods.splice(index, 1);
    
    this.setData({
      'editData.foods': foods
    });
  },
  
  // 取消编辑
  cancelEdit() {
    // 重置编辑数据
    this.setData({
      editData: {
        date: this.data.meal.date,
        time: this.data.meal.time,
        mealType: this.data.meal.mealType,
        foods: this.data.meal.foods.map(food => ({
          ...food,
          quantity: food.quantity || 100,
          unit: food.unit || '克'
        }))
      },
      isEditing: false
    });
  },
  
  // 保存编辑
  async saveEdit() {
    const { mealId, editData } = this.data;
    
    // 验证必填字段
    if (!editData.date || !editData.time || !editData.mealType) {
      wx.showToast({
        title: '请完成所有必填项',
        icon: 'none'
      });
      return;
    }
    
    // 验证是否选择了食物
    if (editData.foods.length === 0) {
      wx.showToast({
        title: '请至少添加一种食物',
        icon: 'none'
      });
      return;
    }
    
    // 准备更新数据
    const mealData = {
      date: editData.date,
      time: editData.time,
      mealType: editData.mealType,
      foods: editData.foods.map(food => ({
        foodId: food._id,
        quantity: parseFloat(food.quantity) || 100,
        unit: food.unit || '克'
      }))
    };
    
    this.setData({ loading: true });
    
    try {
      const result = await api.diet.updateMeal(mealId, mealData);
      
      if (result && result.success) {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        
        // 重新加载餐食详情
        this.loadMealDetail(mealId);
        
        // 退出编辑模式
        this.setData({
          isEditing: false
        });
      } else {
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    } catch (error) {
      console.error('保存编辑失败:', error);
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },
  
  // 删除餐食
  async deleteMeal() {
    try {
      this.setData({ loading: true, showDeleteModal: false });
      
      const result = await api.diet.deleteMeal(this.data.mealId);
      
      if (result && result.success) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
        
        // 延迟返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({
          title: '删除失败',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    } catch (error) {
      console.error('删除餐食失败:', error);
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  }
});

function calculateProtein(age, gender, weight, physiologicalStatus) {
  // 基于表2的RNI值(推荐摄入量)
  // 蛋白质以g/d为单位

  const proteinTable = {
    male: [
      { range: [0, 0.5], value: 9 },
      { range: [0.5, 1], value: 20 },
      // ...其他年龄段
      { range: [18, 65], value: 65 }
    ],
    female: [
      // ...女性数据
      { range: [18, 65], value: 55 },
      { physiological: 'pregnant_early', value: 55 },
      { physiological: 'pregnant_mid', value: 70 },
      { physiological: 'pregnant_late', value: 85 },
      { physiological: 'breastfeeding', value: 80 }
    ]
  };

  // 查找对应的蛋白质RNI值
  let baseProtein = 60; // 默认值
  
  // 对于成人，蛋白质需求通常按体重计算，如1.0-1.2g/kg体重
  if (age >= 18) {
    return Math.round(weight * 1.0); // 按每公斤体重1.0g蛋白质计算
  }
  
  return baseProtein;
}

function calculateFat(age, calories) {
  // 基于图表中的脂肪AMDR百分比
  let fatPercentage = 0.3; // 默认30%
  
  if (age < 4) {
    fatPercentage = 0.35; // 婴幼儿较高脂肪需求
  }
  
  return Math.round((calories * fatPercentage) / 9); // 脂肪: 9kcal/g
}

function calculateCarbs(age, calories) {
  // 基于碳水化合物EAR和AMDR表
  let carbPercentage = 0.55; // 默认55%
  
  if (age < 1) {
    // 特殊婴儿需求
    return 60; // g/天
  }
  
  return Math.round((calories * carbPercentage) / 4); // 碳水: 4kcal/g
}